import axios from 'axios'
import { debounce, getFakeIp } from './misc'

const TOKEN_KEY = 'APP-TOKEN'

export function setTokenStorage(token: string) {
  localStorage.setItem(TOKEN_KEY, token)
}

export function getTokenStorage() {
  return localStorage.getItem(TOKEN_KEY) ?? ''
}

export function clearTokenStorage() {
  localStorage.removeItem(TOKEN_KEY)
}

export const setUserIPStorage = debounce(() => {
  axios.get('http://api.ipify.org', {
    timeout: 5000,
  }).then((res) => {
    localStorage.setItem('APP-IP', res.data)
  }).catch(() => {
    localStorage.setItem('APP-IP', getFakeIp())
  })
}, 50)

export function getUserIPStorage() {
  if (!localStorage.getItem('APP-IP'))
    setUserIPStorage()

  return localStorage.getItem('APP-IP') || ''
}
